#include <vector>
#include "mapDM.h"
#include <iostream>
using namespace std;


void Mapping_C::topologicalsort()
{

	 m_vnode.resize(m_vgate.size());
	 iterfordfs=m_vnode.size()-1;
	 for(unsigned int iter=0;iter<m_vgate.size();++iter)
	 {
	      m_vgate[iter]->place=iter;
	 }
	 
	 //---------------------------------topological sort
	 for(unsigned int iter=0; iter < m_vgate.size();++iter)
	 {
             if(m_vgate[iter]->visit==0)
	     {
                  DFS(m_vgate[iter]);
             }
         }
	 //---------------------------------build the connection
	 
	 vector<int> changeplace;
	 changeplace.resize(m_vnode.size());
	 for(unsigned int iter=0;iter< m_vnode.size();++iter)
	 {
	      int temp;
  	      temp=m_vnode[iter]->id;
	      changeplace[temp]=iter;
	 }
	 
     for(unsigned int nodeiter=0;nodeiter<m_vnode.size();++nodeiter)
	 {
	      int nodeid;
		  nodeid=m_vnode[nodeiter]->id;
		  for(unsigned int i=0;i<m_vgate[nodeid]->input.size();++i)
		  {
		       int gateid;
		       gateid=m_vgate[nodeid]->input[i]->place;
	           int change;
		       change=changeplace[gateid];
		       m_vnode[nodeiter]->input.push_back(m_vnode[change]);
		  }
		  
		  for(unsigned int i=0;i<m_vgate[nodeid]->output.size();++i)
		  {
		         int gateid;
		         gateid=m_vgate[nodeid]->output[i]->place;
	          	 int change;
		         change=changeplace[gateid];
			 m_vnode[nodeiter]->output.push_back(m_vnode[change]);
		  }
	 }
}

void Mapping_C::DFS(Gate* gate)
{
     gate->visit=1;
     
     for(unsigned int i=0;i<gate->output.size();++i)
     {
         if(gate->output[i]->visit==0)
	 {
               DFS(gate->output[i]);
         }
     }
     
     m_vnode[iterfordfs] = new Node_C(gate->place);
     m_vnode[iterfordfs]->type = gate->id;
	 if (gate->id==8)
	 {
		m_vnode[iterfordfs]->name=gate->outputname;
	 }
	 else if (gate->id==9)
	 {
		m_vnode[iterfordfs]->name=gate->inputname[0];
	 }
	 
     iterfordfs--;
}
